using NuGet.Versioning;

namespace NuGetUpdater.Core.Analyze;

public static class SecurityVulnerabilityExtensions
{
    // This logic taken from Dependabot security_advisory.rb
    public static bool IsVulnerable(this SecurityVulnerability vulnerability, NuGetVersion version)
    {
        var inSafeRange = vulnerability.SafeVersions
            .Any(r => r.IsSatisfiedBy(version));
        if (inSafeRange)
        {
            // If version is known safe for this advisory, it's not vulnerable
            return false;
        }

        var inVulnerableRange = vulnerability.VulnerableVersions
            .Any(r => r.IsSatisfiedBy(version));
        if (inVulnerableRange)
        {
            // If in the vulnerable range and not known safe, it's vulnerable
            return true;
        }

        if (vulnerability.VulnerableVersions.Length > 0)
        {
            // If a vulnerable range present but not met, it's not vulnerable
            return false;
        }

        // Finally, if no vulnerable range provided, but a safe range provided,
        // and this versions isn't included (checked earlier), it's vulnerable
        return vulnerability.SafeVersions.Length > 0;
    }
}
